package net.appportal.ant.tasks;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.TaskContainer;

import ca.beq.util.win32.registry.RegistryException;

public class FileReaderTask extends Task implements TaskContainer
{
	private Vector tasks = new Vector();
	private String file = null;
	private boolean verbose = false;
	private String property = null;	
	private boolean failonerror = true;
   
	
	/**
	 * 
	 * @param verbose
	 */
	public void setVerbose( boolean verbose )
	{
		this.verbose = verbose;
	}
	
	/**
	 * 
	 *
	 */
	public FileReaderTask()
	{
		
	}
	
	/**
	 * 
	 * @param property
	 */
	public void setProperty( String property ) 
	{
		this.property = property;
	}	
	
	/**
	 * 
	 * @param name
	 */
	public void setFile( String file )
	{
		this.file = file;
	}

	/**
	 * @throws  
	 * @throws  
	 * 
	 */
	public void execute() throws BuildException 
	{
		BufferedReader reader = null;
		
		try 
		{
			if ( property == null || property.equals( "" ) ) 
				throw new BuildException( "The 'property' attribute is required with 'filereader'." );
			
			if ( file == null || file.equals( "" ) ) 
				throw new BuildException( "The 'file' attribute is required with 'filereader'." );		
			
			StringBuffer sb = new StringBuffer(); 		
			String fileFullPath = Project.translatePath(file);
			String line = null;
	
			reader = new BufferedReader(new FileReader(fileFullPath));
			while ( ( line = reader.readLine() ) != null )
				sb.append(line);
			
			getProject().setUserProperty(property,sb.toString());		
		}
		catch (Exception e) 
		{
			if (e instanceof BuildException) 
			{
				throw new BuildException(e);
			}
			else
			{
				if (failonerror)
				{
					throw new BuildException(e);
				}				
			}
		}
		finally
		{
			if (reader!=null)
			{
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 
	 */
	public void addTask( Task task ) 
	{
	      tasks.addElement( task );		
	}
}
